package com.example.mydy;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.cardview.widget.CardView;
import androidx.appcompat.widget.Toolbar;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.model.CommonResponse;
import com.example.mydy.model.Project;
import com.example.mydy.utils.NetworkUtils;
import com.example.mydy.api.ApiClient;
import com.example.mydy.api.UserApi;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Path;

import com.example.mydy.adapter.ProjectAdapter;

public class ProjectManagementActivity extends AppCompatActivity implements ProjectAdapter.OnProjectActionListener {
    private static final String TAG = "ProjectDebug";
    private static final int PICK_IMAGE_REQUEST = 1;
    private static final String TOKEN_KEY = "token";
    private static final int REQUEST_STORAGE_PERMISSION = 1;
    private static final int REQUEST_PUBLISH_PROJECT = 1;

    // RetrofitClient 完整代码
    private static class RetrofitClient {
        private static Retrofit retrofit;
        private static ProjectManagementActivity activity;

        static void init(ProjectManagementActivity ctx) {
            activity = ctx;
            if (retrofit == null) {
                HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                logging.setLevel(HttpLoggingInterceptor.Level.BODY);

                OkHttpClient client = new OkHttpClient.Builder()
                        .addInterceptor(logging)
                        .addInterceptor(chain -> {
                            String token = activity.getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                                    .getString(TOKEN_KEY, "");

                            Request original = chain.request();
                            Request.Builder builder = original.newBuilder()
                                    .header("Authorization", "Bearer " + token);

                            return chain.proceed(builder.build());
                        })
                        .build();

                retrofit = new Retrofit.Builder()
                        .baseUrl(ApiClient.BASE_URL)
                        .client(client)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
        }

        static Retrofit getInstance() {
            return retrofit;
        }
    }

    // 成员变量
    private EditText etProjectTitle, etProjectDescription, etProjectUnlockFee, etProjectArticle;
    private Button btnPublishProject, navHomeButton, logoutButton, btnSelectImage;
    private RecyclerView projectListRecyclerView;
    private ProjectAdapter projectAdapter;
    private List<Project> projectList = new ArrayList<>();
    private ImageView ivSelectedImage;
    private Uri selectedImageUri;
    private ProgressBar progressBar;
    private Toolbar toolbar;
    private SwipeRefreshLayout swipeRefreshLayout;
    private AlertDialog currentDialog; // 添加对话框成员变量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_project_management);

        // 初始化视图
            initViews();
        
        // 设置RecyclerView
        projectListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        projectAdapter = new ProjectAdapter(this, projectList, "admin", this);
        projectListRecyclerView.setAdapter(projectAdapter);
        
        // 加载项目列表
        loadProjectList();
        
        // 设置刷新按钮点击事件
        findViewById(R.id.btn_refresh).setOnClickListener(v -> {
            // 不通过SwipeRefreshLayout触发刷新，直接调用加载方法
            Toast.makeText(this, "正在刷新...", Toast.LENGTH_SHORT).show();
            loadProjectList();
        });
        
        // 设置悬浮按钮点击事件
        FloatingActionButton fabAddProject = findViewById(R.id.fab_add_reward);
        if (fabAddProject != null) {
            fabAddProject.setOnClickListener(v -> showAddProjectDialog());
        }

        setupToolbar();
        setupSwipeRefresh();
    }

    private void initViews() {
        // 初始化进度条
        progressBar = findViewById(R.id.progress_bar);
        
        // 初始化RecyclerView
            projectListRecyclerView = findViewById(R.id.rv_rewards);

        toolbar = findViewById(R.id.toolbar_reward_management);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
    }

    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("项目管理");
            
            // 设置导航按钮点击事件
            toolbar.setNavigationOnClickListener(v -> {
                Intent intent = new Intent(this, AdminActivity.class);
                startActivity(intent);
                finish();
            });
        }
    }

    private void setupSwipeRefresh() {
        swipeRefreshLayout.setOnRefreshListener(this::loadProjectList);
    }

    // 发布项目
    private void publishProject(View view) {
        String title = etProjectTitle.getText().toString().trim();
        String description = etProjectDescription.getText().toString().trim();
        String unlockFeeStr = etProjectUnlockFee.getText().toString().trim();
        String article = etProjectArticle.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(title) || TextUtils.isEmpty(description) || TextUtils.isEmpty(unlockFeeStr) || TextUtils.isEmpty(article)) {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
            return;
        }

        if (selectedImageUri == null) {
            Toast.makeText(this, "请选择一张项目图片", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            double unlockFee = Double.parseDouble(unlockFeeStr);
            
            // 离线模式
        if (NetworkUtils.USE_OFFLINE_MODE) {
                Project project = new Project();
                project.setId(projectList.size() + 1); // 简单的ID生成
                project.setTitle(title);
                project.setDescription(description);
                project.setReward(unlockFee);
                project.setImageUrl(selectedImageUri.toString()); // 保存图片URI
                project.setStatus(Project.STATUS_ACTIVE);
                project.setCreatedAt(new Date());
                project.setCreatorId(1); // 假设当前用户ID为1
                project.setArticle(article); // 保存文章内容
                
                boolean success = MockDataManager.addProject(project);
                
                if (success) {
                    Toast.makeText(this, "项目已成功发布（离线模式）", Toast.LENGTH_SHORT).show();
                    clearInputFields();
                    // 直接更新列表，而不是重新加载
                    projectList.add(project);
                    projectAdapter.notifyItemInserted(projectList.size() - 1);
                    projectListRecyclerView.scrollToPosition(projectList.size() - 1);
                } else {
                    Toast.makeText(this, "项目发布失败", Toast.LENGTH_SHORT).show();
            }
            return;
        }

            // 在线模式代码
            progressBar.setVisibility(View.VISIBLE);
            
            // 处理图片上传
            String imagePath = getPathFromUri(selectedImageUri);
            if (imagePath == null) {
                Toast.makeText(this, "无法获取图片路径", Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
                return;
            }
            
            // 创建项目对象
            Project project = new Project();
            project.setTitle(title);
            project.setDescription(description);
            project.setReward(unlockFee);
            project.setArticle(article);

        UserApi api = RetrofitClient.getInstance().create(UserApi.class);
            String token = getSharedPreferences("MyAppPrefs", MODE_PRIVATE).getString(TOKEN_KEY, "");
            
            // 在线模式上传项目
            progressBar.setVisibility(View.VISIBLE);
            
            // 创建API调用
            Call<CommonResponse> call = api.createProject("Bearer " + token, project);
            call.enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    progressBar.setVisibility(View.GONE);
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        Toast.makeText(ProjectManagementActivity.this, "项目已成功发布", Toast.LENGTH_SHORT).show();
                        clearInputFields();
                        loadProjectList(); // 重新加载项目列表
                    } else {
                        Toast.makeText(ProjectManagementActivity.this, "项目发布失败: " + 
                                       (response.body() != null ? response.body().getMessage() : "未知错误"), 
                                       Toast.LENGTH_SHORT).show();
                    }
                }
                
                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(ProjectManagementActivity.this, "网络请求失败: " + t.getMessage(), 
                                  Toast.LENGTH_SHORT).show();
                }
            });
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的解锁费用", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 清除输入字段
    private void clearInputFields() {
        etProjectTitle.setText("");
        etProjectDescription.setText("");
        etProjectUnlockFee.setText("");
        etProjectArticle.setText("");
        ivSelectedImage.setImageResource(android.R.color.transparent);
        ivSelectedImage.setVisibility(View.GONE);
        selectedImageUri = null;
    }

    // 加载项目列表
    private void loadProjectList() {
        // 防止重复加载和UI泄漏
        if (!isFinishing() && !isDestroyed()) {
            progressBar.setVisibility(View.VISIBLE);
            
            // 确保刷新状态被重置
            if (swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
            
            // 在线模式代码
            try {
                UserApi api = RetrofitClient.getInstance().create(UserApi.class);
                String token = getSharedPreferences("MyAppPrefs", MODE_PRIVATE).getString(TOKEN_KEY, "");
                
                Call<CommonResponse> call = api.getAllProjects("Bearer " + token);
                call.enqueue(new Callback<CommonResponse>() {
                    @Override
                    public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                        if (!isFinishing() && !isDestroyed()) {
                            progressBar.setVisibility(View.GONE);
                            swipeRefreshLayout.setRefreshing(false);
                            
                            if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                                projectList.clear();
                                // 处理response.body().getData()将其转换为Project列表
                                Object data = response.body().getData();
                                List<Project> projects = new ArrayList<>();
                                
                                if (data instanceof List) {
                                    for (Object item : (List) data) {
                                        if (item instanceof Map) {
                                            Map<String, Object> map = (Map<String, Object>) item;
                                            Project project = new Project();
                                            
                                            // 填充项目数据
                                            if (map.containsKey("id")) {
                                                project.setId(((Double) map.get("id")).intValue());
                                            }
                                            
                                            if (map.containsKey("title")) {
                                                project.setTitle((String) map.get("title"));
                                            }
                                            
                                            if (map.containsKey("description")) {
                                                project.setDescription((String) map.get("description"));
                                            }
                                            
                                            if (map.containsKey("reward")) {
                                                project.setReward((Double) map.get("reward"));
                                            }
                                            
                                            if (map.containsKey("imageUrl")) {
                                                project.setImageUrl((String) map.get("imageUrl"));
                                            }
                                            
                                            if (map.containsKey("article")) {
                                                project.setArticle((String) map.get("article"));
                                            }
                                            
                                            projects.add(project);
                                        }
                                    }
                                }
                                
                                projectList.addAll(projects);
                                projectAdapter.updateProjects(projectList);
                                Log.d(TAG, "成功获取项目列表，数量: " + projectList.size());
                            } else {
                                Log.e(TAG, "获取项目列表失败: " + response.code());
                                Toast.makeText(ProjectManagementActivity.this, 
                                              "获取项目列表失败: " + (response.body() != null ? response.body().getMessage() : "错误码: " + response.code()), 
                                              Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResponse> call, Throwable t) {
                        if (!isFinishing() && !isDestroyed()) {
                            progressBar.setVisibility(View.GONE);
                            swipeRefreshLayout.setRefreshing(false);
                            
                            Log.e(TAG, "获取项目列表请求失败: " + t.getMessage());
                            Toast.makeText(ProjectManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            } catch (Exception e) {
                // 处理任何可能的异常
                Log.e(TAG, "请求过程中出现异常: " + e.getMessage());
                progressBar.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(this, "加载失败，请稍后重试", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 显示编辑项目对话框
    private void showEditProjectDialog(Project project, int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_project, null);
        builder.setView(view);
        
        EditText etEditTitle = view.findViewById(R.id.et_edit_project_title);
        EditText etEditDescription = view.findViewById(R.id.et_edit_project_description);
        EditText etEditArticle = view.findViewById(R.id.et_edit_project_article);
        EditText etEditUnlockFee = view.findViewById(R.id.et_edit_project_unlock_fee);
        Button btnEditSelectImage = view.findViewById(R.id.btn_edit_select_image);
        ImageView ivEditPreview = view.findViewById(R.id.iv_edit_selected_image);
        
        // 填充现有数据
        etEditTitle.setText(project.getTitle());
        etEditDescription.setText(project.getDescription());
        etEditArticle.setText(project.getArticle());
        etEditUnlockFee.setText(String.valueOf(project.getReward()));
        
        // 设置图片
        Uri imageUri = Uri.parse(project.getImageUrl());
        selectedImageUri = imageUri;
        try {
            Picasso.get().load(imageUri).into(ivEditPreview);
            ivEditPreview.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            Log.e(TAG, "加载图片失败: " + e.getMessage());
        }
        
        // 选择新图片
        btnEditSelectImage.setOnClickListener(v -> {
            // 保存当前对话框状态，在选择图片后恢复
            openImageChooser();
        });
        
        builder.setTitle("编辑项目")
               .setPositiveButton("保存", null)
               .setNegativeButton("取消", null);
        
        AlertDialog dialog = builder.create();
        dialog.show();
        
        // 设置保存按钮的点击事件
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            String title = etEditTitle.getText().toString().trim();
            String description = etEditDescription.getText().toString().trim();
            String article = etEditArticle.getText().toString().trim();
            String unlockFeeStr = etEditUnlockFee.getText().toString().trim();
            
            if (TextUtils.isEmpty(title) || TextUtils.isEmpty(description) || 
                TextUtils.isEmpty(article) || TextUtils.isEmpty(unlockFeeStr)) {
                Toast.makeText(this, "所有字段都必须填写", Toast.LENGTH_SHORT).show();
                return;
            }
            
            try {
                double unlockFee = Double.parseDouble(unlockFeeStr);
                
                // 离线模式下直接更新
                if (NetworkUtils.USE_OFFLINE_MODE) {
                    project.setTitle(title);
                    project.setDescription(description);
                    project.setArticle(article);
                    project.setReward(unlockFee);
                    if (selectedImageUri != null) {
                        project.setImageUrl(selectedImageUri.toString());
                    }
                    
                    // 使用MockDataManager更新项目
                    boolean success = MockDataManager.updateProject(project);
                    
                    if (success) {
                        loadProjectList(); // 重新加载项目列表以显示最新数据
                        Toast.makeText(this, "项目更新成功（离线模式）", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "项目更新失败", Toast.LENGTH_SHORT).show();
                    }
                    currentDialog.dismiss();
                    return;
                }
                
                // TODO: 实现在线模式的项目更新
                Toast.makeText(this, "项目更新成功", Toast.LENGTH_SHORT).show();
                currentDialog.dismiss();
                
            } catch (NumberFormatException e) {
                Toast.makeText(this, "解锁费用必须是数字", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    // 确认删除项目
    private void confirmDeleteProject(Project project, int position) {
        new AlertDialog.Builder(this)
            .setTitle("确认删除")
            .setMessage("确定要删除项目 \"" + project.getTitle() + "\" 吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                // 离线模式下使用MockDataManager删除
                if (NetworkUtils.USE_OFFLINE_MODE) {
                    boolean success = MockDataManager.deleteProject(project.getId());
                    if (success) {
                        // 直接更新列表，而不是重新加载
                        projectList.remove(position);
                        projectAdapter.updateProjects(projectList);
                        Toast.makeText(this, "项目已删除（离线模式）", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "删除项目失败", Toast.LENGTH_SHORT).show();
                    }
                    return;
                }
                
                // TODO: 实现在线模式的项目删除
                Toast.makeText(this, "项目已删除", Toast.LENGTH_SHORT).show();
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void logout() {
        SharedPreferences.Editor editor = getSharedPreferences("MyAppPrefs", MODE_PRIVATE).edit();
        editor.putBoolean("isLoggedIn", false);
        editor.putString("token", "");
        editor.putString("username", "");
        editor.apply();

        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    private void showAddProjectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_add_project, null);
        builder.setView(view);
        
        // 初始化对话框中的视图
        EditText etProjectTitle = view.findViewById(R.id.et_project_title);
        EditText etProjectDescription = view.findViewById(R.id.et_project_description);
        EditText etProjectArticle = view.findViewById(R.id.et_project_article);
        EditText etProjectUnlockFee = view.findViewById(R.id.et_project_unlock_fee);
        Button btnSelectImage = view.findViewById(R.id.btn_select_image);
        ImageView ivSelectedImage = view.findViewById(R.id.iv_selected_image);
        Button btnPublishProject = view.findViewById(R.id.btn_publish_project);
        
        // 设置图片选择按钮点击事件
        btnSelectImage.setOnClickListener(v -> {
            if (checkPermission()) {
                openImageChooser();
            } else {
                requestPermission();
            }
        });
        
        // 设置发布按钮点击事件
        btnPublishProject.setOnClickListener(v -> {
            String title = etProjectTitle.getText().toString().trim();
            String description = etProjectDescription.getText().toString().trim();
            String article = etProjectArticle.getText().toString().trim();
            String unlockFeeStr = etProjectUnlockFee.getText().toString().trim();
            
            if (TextUtils.isEmpty(title) || TextUtils.isEmpty(description) || 
                TextUtils.isEmpty(article) || TextUtils.isEmpty(unlockFeeStr)) {
                Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (selectedImageUri == null) {
                Toast.makeText(this, "请选择一张项目图片", Toast.LENGTH_SHORT).show();
                return;
            }
            
            try {
                double unlockFee = Double.parseDouble(unlockFeeStr);
            
            // 离线模式
            if (NetworkUtils.USE_OFFLINE_MODE) {
                Project project = new Project();
                    project.setId(projectList.size() + 1);
                project.setTitle(title);
                project.setDescription(description);
                    project.setReward(unlockFee);
                    project.setImageUrl(selectedImageUri.toString());
                    project.setStatus(Project.STATUS_ACTIVE);
                    project.setCreatedAt(new Date());
                    project.setCreatorId(1);
                    project.setArticle(article);
                    
                    boolean success = MockDataManager.addProject(project);
                    
                    if (success) {
                        projectList.add(project);
                        projectAdapter.notifyItemInserted(projectList.size() - 1);
                        projectListRecyclerView.scrollToPosition(projectList.size() - 1);
                        Toast.makeText(this, "项目发布成功（离线模式）", Toast.LENGTH_SHORT).show();
                        currentDialog.dismiss(); // 使用成员变量关闭对话框
                    } else {
                        Toast.makeText(this, "项目发布失败", Toast.LENGTH_SHORT).show();
                    }
                    return;
                }
                
                // 在线模式代码
        progressBar.setVisibility(View.VISIBLE);
        
                // 处理图片上传
                String imagePath = getPathFromUri(selectedImageUri);
                if (imagePath == null) {
                    Toast.makeText(this, "无法获取图片路径", Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                    return;
                }
                
                // 创建项目对象
                Project project = new Project();
                project.setTitle(title);
                project.setDescription(description);
                project.setReward(unlockFee);
                project.setArticle(article);
                
                UserApi api = RetrofitClient.getInstance().create(UserApi.class);
                String token = getSharedPreferences("MyAppPrefs", MODE_PRIVATE).getString(TOKEN_KEY, "");
                
                // 在线模式上传项目
                progressBar.setVisibility(View.VISIBLE);
                
                // 创建API调用
                Call<CommonResponse> call = api.createProject("Bearer " + token, project);
                call.enqueue(new Callback<CommonResponse>() {
                    @Override
                    public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                        progressBar.setVisibility(View.GONE);
                        if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                            Toast.makeText(ProjectManagementActivity.this, "项目已成功发布", Toast.LENGTH_SHORT).show();
                            clearInputFields();
                            loadProjectList(); // 重新加载项目列表
                        } else {
                            Toast.makeText(ProjectManagementActivity.this, "项目发布失败: " + 
                                           (response.body() != null ? response.body().getMessage() : "未知错误"), 
                                           Toast.LENGTH_SHORT).show();
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<CommonResponse> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(ProjectManagementActivity.this, "网络请求失败: " + t.getMessage(), 
                                      Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (NumberFormatException e) {
                Toast.makeText(this, "请输入有效的解锁费用", Toast.LENGTH_SHORT).show();
            }
        });
        
        builder.setTitle("发布新项目")
               .setNegativeButton("取消", null);
        
        currentDialog = builder.create(); // 将对话框保存为成员变量
        currentDialog.show();
    }

    @Override
    public void onProjectClick(Project project) {
        // 处理项目点击事件
        Intent intent = new Intent(this, ProjectDetailActivity.class);
        intent.putExtra("projectId", project.getId());
        startActivity(intent);
    }

    @Override
    public void onUnlockButtonClick(Project project) {
        // 管理界面不需要解锁功能，但需要实现接口方法
        // 可以考虑在这里实现编辑功能
        showEditProjectDialog(project, projectList.indexOf(project));
    }

    public interface UserApi {
        @Multipart
        @POST("projects")
        Call<CommonResponse> publishProject(
                @Part("title") RequestBody title,
                @Part("description") RequestBody description,
                @Part("article") RequestBody article,
                @Part("unlockFee") RequestBody unlockFee,
                @Part MultipartBody.Part image
        );

        @GET("projects")
        Call<List<Project>> getProjects();

        @POST("projects")
        Call<Project> createProject(
                @Header("Authorization") String authorization,
                @Body Project project
        );

        @GET("projects")
        Call<List<Project>> getAllProjects(
                @Header("Authorization") String authorization
        );

        @POST("projects/{id}")
        Call<CommonResponse> updateProject(
                @Header("Authorization") String authorization,
                @Path("id") int id,
                @Body Project project
        );

        @DELETE("projects/{id}")
        Call<CommonResponse> deleteProject(
                @Header("Authorization") String authorization,
                @Path("id") int id
        );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openImageChooser();
            } else {
                Toast.makeText(this, "需要存储权限以选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 从URI获取文件路径
    private String getPathFromUri(Uri uri) {
        try {
            if ("content".equalsIgnoreCase(uri.getScheme())) {
                String[] projection = {MediaStore.Images.Media.DATA};
                Cursor cursor = null;
                
                try {
                    cursor = getContentResolver().query(uri, projection, null, null, null);
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    if (cursor.moveToFirst()) {
                        return cursor.getString(column_index);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "获取文件路径失败: " + e.getMessage());
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }

            // 如果上述方法无法获取路径，直接返回URI字符串
            return uri.toString();
        } catch (Exception e) {
            Log.e(TAG, "URI处理异常: " + e.getMessage());
            return null;
        }
    }

    // 添加权限检查方法
    private boolean checkPermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED;
    }

    // 添加权限请求方法
    private void requestPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_STORAGE_PERMISSION);
    }

    // 添加图片选择方法
    private void openImageChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            selectedImageUri = data.getData();
            if (selectedImageUri != null) {
            try {
                    Picasso.get().load(selectedImageUri).into(ivSelectedImage);
                ivSelectedImage.setVisibility(View.VISIBLE);
                } catch (Exception e) {
                    Log.e(TAG, "加载图片失败: " + e.getMessage());
                }
            }
        } else if (requestCode == REQUEST_PUBLISH_PROJECT && resultCode == RESULT_OK && data != null) {
            Project project = (Project) data.getSerializableExtra("project");
            if (project != null) {
                projectList.add(project);
                projectAdapter.notifyItemInserted(projectList.size() - 1);
                projectListRecyclerView.scrollToPosition(projectList.size() - 1);
                Toast.makeText(this, "项目发布成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 修改updateProject方法，将项目更新保存到服务器
    private void updateProject(Project project, int position) {
        progressBar.setVisibility(View.VISIBLE);
        
        try {
            UserApi api = RetrofitClient.getInstance().create(UserApi.class);
            String token = getSharedPreferences("MyAppPrefs", MODE_PRIVATE).getString(TOKEN_KEY, "");
            
            Call<CommonResponse> call = api.updateProject("Bearer " + token, project.getId(), project);
            call.enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    progressBar.setVisibility(View.GONE);
                    
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        Toast.makeText(ProjectManagementActivity.this, "项目更新成功", Toast.LENGTH_SHORT).show();
                        
                        // 更新本地项目列表
                        projectList.set(position, project);
                        projectAdapter.notifyItemChanged(position);
                    } else {
                        Log.e(TAG, "项目更新失败: " + response.code());
                        Toast.makeText(ProjectManagementActivity.this, 
                                      "项目更新失败: " + (response.body() != null ? response.body().getMessage() : "错误码: " + response.code()), 
                                      Toast.LENGTH_SHORT).show();
                    }
                }
                
                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    progressBar.setVisibility(View.GONE);
                    Log.e(TAG, "项目更新请求失败: " + t.getMessage());
                    Toast.makeText(ProjectManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            progressBar.setVisibility(View.GONE);
            Log.e(TAG, "更新项目时出现异常: " + e.getMessage());
            Toast.makeText(this, "更新失败，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }

    // 修改deleteProject方法，从服务器删除项目
    private void deleteProject(Project project, int position) {
        progressBar.setVisibility(View.VISIBLE);
        
        try {
            UserApi api = RetrofitClient.getInstance().create(UserApi.class);
            String token = getSharedPreferences("MyAppPrefs", MODE_PRIVATE).getString(TOKEN_KEY, "");
            
            Call<CommonResponse> call = api.deleteProject("Bearer " + token, project.getId());
            call.enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    progressBar.setVisibility(View.GONE);
                    
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        Toast.makeText(ProjectManagementActivity.this, "项目删除成功", Toast.LENGTH_SHORT).show();
                        
                        // 更新本地项目列表
                        projectList.remove(position);
                        projectAdapter.notifyItemRemoved(position);
                    } else {
                        Log.e(TAG, "项目删除失败: " + response.code());
                        Toast.makeText(ProjectManagementActivity.this, 
                                      "项目删除失败: " + (response.body() != null ? response.body().getMessage() : "错误码: " + response.code()), 
                                      Toast.LENGTH_SHORT).show();
                    }
                }
                
                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    progressBar.setVisibility(View.GONE);
                    Log.e(TAG, "项目删除请求失败: " + t.getMessage());
                    Toast.makeText(ProjectManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            progressBar.setVisibility(View.GONE);
            Log.e(TAG, "删除项目时出现异常: " + e.getMessage());
            Toast.makeText(this, "删除失败，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }
}